#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月13日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
from localConfig import baseLocalConfig

import logging,re
from PyMySQL import ConnectMySQL


datatuning_host = baseLocalConfig.mysqlConfig['datatuning']['host']
datatuning_port = baseLocalConfig.mysqlConfig['datatuning']['port']
datatuning_user = baseLocalConfig.mysqlConfig['datatuning']['user']
datatuning_passwd = baseLocalConfig.mysqlConfig['datatuning']['passwd']
datatuning_db = baseLocalConfig.mysqlConfig['datatuning']['db']
myDatatuning = ConnectMySQL(host=datatuning_host, user=datatuning_user, password=datatuning_passwd, db=datatuning_db)


class ZhimindRoleDatas(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
    
    def getRoleFromHiveFile(self,day=None,groups = [],rawpath='/Udisk/new_role/',timeRange=None,roles=[1,-1,3,10]):
        rfile = '%s/%s/part-00000'%day
        #2015-08-01,32013138,d8:bb:2c:f0:60:73,2015-08-01 18:10:48,2015-08-01 18:10:48,0,1,Apple
        datas = {}
        if timeRange!=None and re.search('[\d]{2}:[\d]{2}:[\d]{2},[\d]{2}:[\d]{2}:[\d]{2}',timeRange):
            min_time,max_time = timeRange.split(',')
        elif timeRange == None:
            min_time = '00:00:00'
            max_time = '23:59:59'
        else:
            logging.error('timeRange %s fromat Error,use default min and max time.'%timeRange)
            min_time = '00:00:00'
            max_time = '23:59:59'
        
        if not os.path.exists(rfile):
            logging.error('role file %s not exists'%rfile)
            return datas
        for line in open(rfile).read().split('\n'):
            pass
            lineList = line.split(',')
            if len(lineList) < 8:continue
            group = lineList[1]
            if group not in groups:continue
            mac = lineList[2]
            st = lineList[3][11:]
            et = lineList[4][11:]
            if st < min_time or st > max_time:continue 
            
            dur = lineList[5]
            role = lineList[6]
            if int(role) not in roles:continue
            fac = lineList[7]
            if group not in datas.keys():
                datas[group] = {}
            if mac not in datas[group].keys():
                datas[group][mac] = []
                
            datas[group][mac].append({'st':st,'et':et,'dur':dur,'role':role,'fac':fac})
        return datas
    
    
    def get_all_customer_dur_data(self,tab='customer',group=None,startTime=None,endTime=None):
        query = 'select mac,dur from %s where dgroup="%s" and day between "%s" and "%s" and role in (3,10)'%(tab,group,startTime,endTime)
        rets = myDatatuning.SelectAll(query)
        if rets==None:rets = []
        datas = []
        for ret in rets:
            mac,dur = datas
            
    def get_customer_count_by_dur(self,tab='customer',groups=[],startTime=None,endTime=None,minDur=0,maxDur=3600*24*1000):
        if groups==[]:
            return '-'
        if len(groups)==1:
            groups_str = "%s"%groups[0]
        else:
            groups_str = '"'+'","'.join(groups)+'"'
        query = 'select * from %s where dgroup in (%s) and day between "%s" and "%s" and role in (3,10) and dur between "%s" and "%s"'%(tab,groups_str,startTime,endTime,minDur,maxDur)
        
        ret = myDatatuning.selectCount(query)
        return ret
    def get_visit_freq(self,tab='customer',groups=[],startTime=None,endTime=None,freqTypes={'1':'1:1','2':'2:2','3':'3:3','4':'4:4','5':'5:99'}):
        datas = {}
        if groups==[]:return datas
        groups_str = self.conv_tuple_to_str(groups)
        query = 'select mac,count(*) from %s where dgroup in (%s) and day between "%s" and "%s" group by mac'%(tab,groups_str,startTime,endTime)
        rets = myDatatuning.SelectAll(query)
        if rets ==None:rets = []
        
        for ret in rets:
            mac,sum_visit_freq = ret
            for freqType,freqValues in freqTypes.iteritems():
                freq_min,freq_max = freqValues.split(':')
                if freq_min<=sum_visit_freq<=freq_max:
                    if freqType not in datas.keys():
                        datas[freqType] = 0
                    datas[freqType] = datas[freqType] +1
        return datas
    
myZhimindRoleDatas = ZhimindRoleDatas()      
if __name__ == '__main__':
    myZhimindRoleDatas = ZhimindRoleDatas()
    myZhimindRoleDatas.get_all_customer_data(group=32010464, startTime='2014-11-01', endTime='2015-02-28')